package com.it.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.it.common.R;
import com.it.domain.DTO.InventoryListDTO;
import com.it.domain.DTO.InventoryQueryDTO;
import com.it.domain.Inventory;
import com.it.domain.PageResult;
import com.it.domain.ResponseResult;

import com.it.pojo.*;
import com.it.service.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/mobile")
public class MobileController {
    @Autowired
    private FinancialReportService financialReportService;
    @Autowired
    private SalesOrderService2 salesOrderService2;
    @Autowired
    private CustomerService2 customerService2;
    @Autowired
    private IInventoryService inventoryService;
    @Autowired
    private UserService userService;
    @Autowired
    private PurchaseOrderService purchaseOrderService;
    @Autowired
    private SupplierService supplierService;
    @PostMapping("/login")
    public ResponseEntity<Map<String, Object>> login(@RequestBody Map<String, String> credentials,HttpSession session) {
        String username = credentials.get("username");
        String password = credentials.get("password");
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUsername,username);
        lqw.eq(User::getPassword,password);
        User user = userService.getOne(lqw);
        session.setAttribute("user",user);
        return ResponseEntity.ok(Map.of(
                "success", true,
                "data", Map.of(
                        "userId", user.getUserId(),
                        "username", user.getUsername(),
                        "roleId", user.getRoleId()

                )
        ));
    }
    @PostMapping("/logout")
    public R logout(HttpSession session) {
        // 删除session内容
        session.removeAttribute("user");
        return R.success("退出成功");
    }
    @GetMapping("/locations")
    public ResponseResult<List<String>> getAvailableLocations() {
        // 1. 查询所有不重复的仓库位置
        List<String> locations = inventoryService.list()
                .stream()
                .map(Inventory::getLocation)
                .distinct()
                .collect(Collectors.toList());

        // 2. 如果没有数据返回空列表而不是null
        if (locations.isEmpty()) {
            return ResponseResult.success(Collections.emptyList());
        }
        return ResponseResult.success(locations);
    }
    @GetMapping("/select")
    public ResponseResult<PageResult<InventoryListDTO>> selectInventory(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer pageSize,
            @RequestParam(required = false) Integer productId,
            InventoryQueryDTO queryDTO) {

        // 1. 构建查询条件
        LambdaQueryWrapper<Inventory> queryWrapper = new LambdaQueryWrapper<Inventory>()
                .eq(productId != null, Inventory::getProductId, productId)
                .eq(queryDTO.getProductId() != null, Inventory::getProductId, queryDTO.getProductId())
                .like(StringUtils.isNotBlank(queryDTO.getLocation()), Inventory::getLocation, queryDTO.getLocation())
                .orderByDesc(Inventory::getInventoryId);

        // 2. 执行分页查询
        Page<Inventory> pageResult = inventoryService.page(new Page<>(page, pageSize), queryWrapper);

        // 3. 转换为DTO列表
        List<InventoryListDTO> dtoList = pageResult.getRecords()
                .stream()
                .map(InventoryListDTO::convertToDTO)
                .collect(Collectors.toList());

        // 4. 返回标准化分页结果
        return ResponseResult.success(
                new PageResult<>(
                        dtoList,
                        pageResult.getTotal(),
                        pageResult.getCurrent(),
                        pageResult.getSize()
                )
        );
    }

    // 转换方法


    @PutMapping("/update/{id}")
    public ResponseResult<String> update(
            @PathVariable Integer id,
            @RequestBody Inventory inventory
    ) {
        inventory.setInventoryId(id); // 确保ID绑定
        boolean success = inventoryService.updateById(inventory);
        //这里没有修改修改人ID
        return success
                ? ResponseResult.success("更新成功")
                : ResponseResult.error("更新失败");
    }
    @PostMapping("/insert")
    public ResponseResult<String>add(@RequestBody Inventory inventory){
        if (inventory.getProductId() == null) {
            return ResponseResult.error("产品ID不能为空");
        }

        if (inventory.getQuantity() == null || inventory.getQuantity() <= 0) {
            return ResponseResult.error("库存数量必须大于0");
        }

        if (inventory.getLocation() == null || inventory.getLocation().isEmpty()) {
            return ResponseResult.error("库存位置不能为空");
        }
        return inventoryService.save(inventory)?ResponseResult.success("新增成功"):ResponseResult.error("新增失败");
    }



    @GetMapping("/getPurchaseOrderList")
    public ResponseResult<Map<String, Object>> getPurchaseOrderList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search,
            @RequestParam(required = false) String status) {

        // MyBatis Plus分页从0开始，前端传的page从1开始，需要-1
        Page<PurchaseOrder> pageInfo = new Page<>(page - 1, pageSize);

        LambdaQueryWrapper<PurchaseOrder> queryWrapper = new LambdaQueryWrapper<>();

        // 搜索条件处理（同时搜索订单ID和供应商名称）
        if (search != null && !search.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like(PurchaseOrder::getPurchaseOrderId, search)
                    .or()
                    .like(PurchaseOrder::getName, search));
        }

        // 状态筛选（前端传小写，转换为大写查询）
        if (status != null && !status.isEmpty()) {
            queryWrapper.eq(PurchaseOrder::getStatus, status.toUpperCase());
        }

        // 按创建时间倒序
        queryWrapper.orderByDesc(PurchaseOrder::getCreateTime);

        Page<PurchaseOrder> orderPage = purchaseOrderService.page(pageInfo, queryWrapper);

        // 转换数据格式适配前端
        List<Map<String, Object>> convertedList = orderPage.getRecords().stream()
                .map(order -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("purchaseOrderId", order.getPurchaseOrderId());
                    map.put("name", order.getName()); // 注意前端使用name字段
                    map.put("totalAmount", order.getTotalAmount());
                    map.put("status", order.getStatus().toLowerCase()); // 状态转小写
                    return map;
                })
                .collect(Collectors.toList());

        return ResponseResult.success(Map.of(
                "list", convertedList,  // 前端需要的字段名
                "total", orderPage.getTotal()
        ));
    }

    @PostMapping("/purchase-order")
    public ResponseResult<String> createPurchaseOrder(@RequestBody PurchaseOrder order,
                                                      HttpServletRequest request) {
        // 获取当前登录用户（根据您的认证系统调整）

        User currentUser = (User) request.getSession().getAttribute("user");
        // 设置创建人和修改人
        order.setCreateBy(currentUser.getCreateBy());
        order.setUpdateBy(currentUser.getUpdateBy());

        // 设置创建时间和修改时间
        order.setCreateTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());

        boolean success = purchaseOrderService.save(order);
        return success
                ? ResponseResult.success("创建成功")
                : ResponseResult.error("创建失败");
    }



    @GetMapping("/purchase-order/{id}")
    public ResponseResult<Map<String, Object>> getPurchaseOrderDetail(@PathVariable Integer id) {
        PurchaseOrder order = purchaseOrderService.getById(id);
        if (order == null) {
            return ResponseResult.error("订单不存在");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> result = new HashMap<>();
        result.put("purchaseOrderId", order.getPurchaseOrderId());
        result.put("name", order.getName()); // 注意前端使用name字段
        result.put("totalAmount", order.getTotalAmount());
        result.put("status", order.getStatus().toLowerCase());
        result.put("createBy",order.getCreateBy());
        result.put("createTime",sdf.format(order.getCreateTime()));
        result.put("updateBy",order.getUpdateBy());
        result.put("updateTime",order.getUpdateTime());
        result.put("orderDate",sdf.format(order.getOrderDate()));
        return ResponseResult.success(result);
    }

    @PutMapping("/purchase-order/{id}")
    public ResponseResult<String> updatePurchaseOrder(
            @PathVariable Integer id,
            @RequestBody PurchaseOrder order) {
        try {
            // 1. 验证订单是否存在
            PurchaseOrder existingOrder = purchaseOrderService.getById(id);
            if (existingOrder == null) {
                return ResponseResult.error("订单不存在");
            }

            // 2. 设置不允许修改的字段（从前端传来的数据中排除）
            order.setPurchaseOrderId(id); // 确保ID一致
            order.setCreateBy(existingOrder.getCreateBy());
            order.setCreateTime(existingOrder.getCreateTime());

            // 3. 设置审计字段（由系统自动维护）
            order.setUpdateBy(order.getUpdateBy()); // 获取当前用户ID
            order.setUpdateTime(LocalDateTime.now());

            // 4. 更新订单
            boolean success = purchaseOrderService.updateById(order);
            return success
                    ? ResponseResult.success("更新成功")
                    : ResponseResult.error("更新失败");
        } catch (Exception e) {
            return ResponseResult.error("更新失败: " + e.getMessage());
        }
    }

    @PutMapping("/purchase-order/{id}/approve")
    public ResponseResult<String> approvePurchaseOrder(@PathVariable Integer id) {
        PurchaseOrder order = new PurchaseOrder();
        order.setPurchaseOrderId(id);
        order.setStatus("approved");
        boolean success = purchaseOrderService.updateById(order);
        return success
                ? ResponseResult.success("审批成功")
                : ResponseResult.error("审批失败");
    }

    @PutMapping("/purchase-order/{id}/reject")
    public ResponseResult<String> rejectPurchaseOrder(@PathVariable Integer id) {
        PurchaseOrder order = new PurchaseOrder();
        order.setPurchaseOrderId(id);
        order.setStatus("rejected");
        boolean success = purchaseOrderService.updateById(order);
        return success
                ? ResponseResult.success("拒绝成功")
                : ResponseResult.error("拒绝失败");
    }
    @GetMapping("/supplier")
    public ResponseResult<Map<String, Object>> getSupplierList(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search) {

        // MyBatis Plus分页从0开始，前端传的page从1开始，需要-1
        Page<Supplier> pageInfo = new Page<>(page - 1, pageSize);

        LambdaQueryWrapper<Supplier> queryWrapper = new LambdaQueryWrapper<>();

        // 搜索条件处理（同时搜索订单ID和供应商名称）
        if (search != null && !search.isEmpty()) {
            queryWrapper.and(wrapper -> wrapper
                    .like(Supplier::getSupplierId, search)
                    .or()
                    .like(Supplier::getName, search));
        }
        // 按创建时间倒序
        queryWrapper.orderByDesc(Supplier::getCreateTime);

        Page<Supplier> orderPage = supplierService.page(pageInfo, queryWrapper);

        // 转换数据格式适配前端
        List<Map<String, Object>> convertedList = orderPage.getRecords().stream()
                .map(order -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("supplierId", order.getSupplierId());
                    map.put("name", order.getName()); // 注意前端使用name字段
                    map.put("contactPerson", order.getContactPerson());
                    map.put("address", order.getAddress());
                    map.put("contactEmail",order.getContactEmail());
                    map.put("contactPhone", order.getContactPhone());
                    return map;
                })
                .collect(Collectors.toList());

        return ResponseResult.success(Map.of(
                "list", convertedList,  // 前端需要的字段名
                "total", orderPage.getTotal()
        ));
    }
    @GetMapping("/supplier/{id}")
    public ResponseResult<Map<String, Object>> getSupplierPDetail(@PathVariable Integer id) {
        Supplier order = supplierService.getById(id);
        if (order == null) {
            return ResponseResult.error("订单不存在");
        }
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> result = new HashMap<>();
        result.put("supplierId", order.getSupplierId());
        result.put("name", order.getName()); // 注意前端使用name字段
        result.put("address", order.getAddress());
        result.put("contactEmail",order.getContactEmail());
        result.put("contactPhone", order.getContactPhone());
        result.put("contactPerson", order.getContactPerson());
        result.put("createBy",order.getCreateBy());
        result.put("createTime", sdf.format(order.getCreateTime()));
        result.put("updateBy",order.getUpdateBy());
        result.put("updateTime",sdf.format(order.getUpdateTime()));
        return ResponseResult.success(result);
    }
    @PutMapping("/supplier/{id}")
    public ResponseResult<Map<String, Object>> update(  // 改为返回Map
                                                        @PathVariable Integer id,
                                                        @RequestBody Map<String, Object> updateFields,
                                                        HttpServletRequest request) {

        // 获取当前用户
        User currentUser = (User) request.getSession().getAttribute("user");
        if (currentUser == null) {
            return ResponseResult.error("未登录或会话已过期");
        }

        // 使用正确的列名
        UpdateWrapper<Supplier> wrapper = new UpdateWrapper<>();
        wrapper.eq("supplierId", id);  // 确保使用数据库列名

        // 添加审计字段
        updateFields.put("updateBy", currentUser.getUserId());
        updateFields.put("updateTime", new Date());

        updateFields.forEach((key, value) -> {
            if (!"createBy".equals(key) && !"createTime".equals(key)) {
                wrapper.set(key, value);
            }
        });

        boolean success = supplierService.update(wrapper);

        // 返回更丰富的响应信息
        Map<String, Object> result = new HashMap<>();
        result.put("success", success);
        result.put("timestamp", System.currentTimeMillis());
        return success
                ? ResponseResult.success(result)
                : ResponseResult.error("更新失败");
    }



    @GetMapping("/sales")
    public Map<String, Object> getSalesOrders(
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        Page<SalesOrder> page1 = new Page<>(page, pageSize);
        // 1. 构建查询条件
        LambdaQueryWrapper<SalesOrder> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(search)) {
            wrapper.like(SalesOrder::getName, search);
        }

        // 2. 执行分页查询
        Page<SalesOrder> pageResult = salesOrderService2.page(
                page1,
                wrapper
        );

        // 3. 手动构建响应结构
        Map<String, Object> response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        response.put("data", Map.of(
                "list", pageResult.getRecords(),
                "total", pageResult.getTotal()
        ));

        return response;
    }

    @PostMapping("/sales")
    public ResponseResult<String> createSalesOrder(@RequestBody com.it.pojo.SalesOrder salesOrder) {
        boolean success = salesOrderService2.createSalesOrder(salesOrder);
        return success ? ResponseResult.success("订单创建成功") : ResponseResult.error("订单创建失败");
    }

    @PutMapping("/sales/{id}")
    public ResponseResult<String> updateSalesOrder(
            @PathVariable Integer id, @RequestBody com.it.pojo.SalesOrder salesOrder) {
        boolean success = salesOrderService2.updateSalesOrder(id, salesOrder);
        return success ? ResponseResult.success("订单更新成功") : ResponseResult.error("订单更新失败");
    }

    @DeleteMapping("/sales/{id}")
    public ResponseResult<String> deleteSalesOrder(@PathVariable Integer id) {
        boolean success = salesOrderService2.deleteSalesOrder(id);
        return success ? ResponseResult.success("订单删除成功") : ResponseResult.error("订单删除失败");
    }


    @GetMapping("/customers")
    public Map<String, Object> getCustomers(
            @RequestParam(required = false) String search,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize) {
        Page<Customer> pageInfo = new Page<>(page - 1, pageSize);

        LambdaQueryWrapper<Customer> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(search)) {
            wrapper.like(Customer::getName, search)
                    .or().like(Customer::getContactPerson, search);
        }

        Page<Customer> pageResult = customerService2.page(
                pageInfo,
                wrapper
        );

        return Map.of(
                "code", 200,
                "data", Map.of(
                        "list", pageResult.getRecords(),
                        "total", pageResult.getTotal()
                )
        );
    }

    @PostMapping("/customers")
    public ResponseResult<String> createCustomer(@RequestBody Customer customer) {
        boolean success = customerService2.createCustomer(customer);
        return success ? ResponseResult.success("客户创建成功") : ResponseResult.error("客户创建失败");
    }

    @PutMapping("/customers/{id}")
    public ResponseResult<String> updateCustomer(
            @PathVariable Integer id, @RequestBody Customer customer) {
        boolean success = customerService2.updateCustomer(id, customer);
        return success ? ResponseResult.success("客户更新成功") : ResponseResult.error("客户更新失败");
    }

    @DeleteMapping("/customers/{id}")
    public ResponseResult<String> deleteCustomer(@PathVariable Integer id) {
        boolean success = customerService2.deleteCustomer(id);
        return success ? ResponseResult.success("客户删除成功") : ResponseResult.error("客户删除失败");
    }



    @GetMapping("/financial/reports")
    public ResponseResult<Page<FinancialReport>> getFinancialReports(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String search) {
        Page<FinancialReport> reports = financialReportService.getFinancialReports(page, pageSize, search);
        return ResponseResult.success(reports);
    }

    @PostMapping("/financial/reports")
    public ResponseResult<Boolean> createFinancialReport(@RequestBody FinancialReport report) {
        boolean result = financialReportService.createFinancialReport(report);
        return result ? ResponseResult.success(true) : ResponseResult.error("创建报表失败");
    }
    @PutMapping("/financial/reports/{id}")
    public ResponseResult<Boolean> updateFinancialReport(@PathVariable Integer id, @RequestBody FinancialReport report) {
        report.setReportId(id);
        boolean result = financialReportService.updateFinancialReport(report);
        return result ? ResponseResult.success(true) : ResponseResult.error("更新报表失败");
    }
    @DeleteMapping("/financial/reports/{id}")
    public ResponseResult<Boolean> deleteFinancialReport(@PathVariable Integer id) {
        boolean result = financialReportService.deleteFinancialReport(id);
        return result ? ResponseResult.success(true) : ResponseResult.error("删除报表失败");
    }
    @GetMapping("/financial/report-types")
    public ResponseResult<List<String>> getReportTypes() {
        List<String> types = financialReportService.getReportTypes();
        return ResponseResult.success(types);
    }
}
